<template>
  <div class="change-password">
    <!-- 头部 -->
    <div class="header">
      <i class="fas fa-arrow-left" @click="goBack"></i>
      <h3>修改密码</h3>
      <div class="header-placeholder"></div>
    </div>

    <!-- 表单内容 -->
    <div class="content">
      <div class="form-section">
        <div class="form-item">
          <label>新密码</label>
          <input
              type="password"
              v-model="formData.newPassword"
              placeholder="请输入新密码"
              :class="{ error: errors.newPassword }"
          >
        </div>

        <div class="form-item">
          <label>确认密码</label>
          <input
              type="password"
              v-model="confirmPassword"
              placeholder="请再次输入新密码"
              :class="{ error: errors.confirmPassword }"
          >
        </div>
      </div>

      <div class="tips">
        <p>• 密码长度至少6位</p>
        <p>• 建议使用字母、数字和符号组合</p>
      </div>

      <button class="save-btn" @click="changePassword" :disabled="saving">
        {{ saving ? '修改中...' : '确认修改' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { userAPI } from '@/api/user.js'
import { useAuthStore } from '@/stores/auth.js' // 导入 auth store

const router = useRouter()
const authStore = useAuthStore() // 使用 auth store
const saving = ref(false)

const formData = ref({
  newPassword: ''
})

const confirmPassword = ref('')

const errors = ref({
  newPassword: false,
  confirmPassword: false
})

// 返回上一页
const goBack = () => {
  router.back()
}

// 验证表单
const validateForm = () => {
  let isValid = true
  errors.value = { newPassword: false, confirmPassword: false }

  if (!formData.value.newPassword.trim()) {
    errors.value.newPassword = true
    isValid = false
  } else if (formData.value.newPassword.length < 6) {
    errors.value.newPassword = true
    alert('密码长度至少6位')
    isValid = false
  }

  if (!confirmPassword.value.trim()) {
    errors.value.confirmPassword = true
    isValid = false
  } else if (formData.value.newPassword !== confirmPassword.value) {
    errors.value.confirmPassword = true
    alert('两次输入的密码不一致')
    isValid = false
  }

  return isValid
}

// 修改密码
const changePassword = async () => {
  if (!validateForm()) {
    return
  }

  saving.value = true
  try {
    // 获取当前登录用户的用户名
    const currentUser = await getCurrentUser()
    const requestData = {
      username: currentUser.username,
      password: formData.value.newPassword
    }

    await userAPI.updateUserPassword(requestData)
    alert('密码修改成功，请重新登录')

    // 清空表单
    formData.value = { newPassword: '' }
    confirmPassword.value = ''

    // 调用登出方法清除认证状态
    authStore.logout()

    // 跳转到登录页面
    router.push('/login')
  } catch (error) {
    console.error('密码修改失败:', error)
    const errorMessage = error.response?.data?.message || '密码修改失败'
    alert(errorMessage)
  } finally {
    saving.value = false
  }
}

// 添加获取当前用户信息的函数
const getCurrentUser = async () => {
  try {
    const response = await userAPI.information()
    // 根据你的API响应结构调整
    if (response.data && response.data.success === true && response.data.data) {
      return response.data.data
    } else if (response.data && response.data.username) {
      return response.data
    }
    throw new Error('无法获取用户信息')
  } catch (error) {
    console.error('获取用户信息失败:', error)
    throw error
  }
}
</script>

<style scoped>
.change-password {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 4vw;
  background: white;
  border-bottom: 1px solid #eee;
}

.header i {
  font-size: 5vw;
  color: #666;
  cursor: pointer;
}

.header h3 {
  font-size: 4.5vw;
  font-weight: normal;
  color: #333;
}

.header-placeholder {
  width: 5vw;
}

.content {
  padding: 4vw;
}

.form-section {
  background: white;
  border-radius: 2vw;
  overflow: hidden;
  margin-bottom: 4vw;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 4vw;
  border-bottom: 1px solid #f0f0f0;
  font-size: 4vw;
}

.form-item:last-child {
  border-bottom: none;
}

.form-item label {
  width: 20vw;
  color: #333;
}

.form-item input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 4vw;
  color: #333;
  background: transparent;
}

.form-item input::placeholder {
  color: #ccc;
}

.form-item input.error {
  color: #ff4757;
}

.tips {
  background: #fff9e6;
  padding: 3vw;
  border-radius: 1vw;
  margin-bottom: 4vw;
  font-size: 3.5vw;
  color: #666;
  line-height: 1.5;
}

.tips p {
  margin-bottom: 1vw;
}

.tips p:last-child {
  margin-bottom: 0;
}

.save-btn {
  width: 100%;
  padding: 4vw;
  background: linear-gradient(135deg, #ff6b6b, #ee5a24);
  color: white;
  border: none;
  border-radius: 2vw;
  font-size: 4.5vw;
  cursor: pointer;
  transition: opacity 0.3s;
}

.save-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.save-btn:active {
  opacity: 0.8;
}
</style>